package wechat

import (
	"baokaobang/utils"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

// 文本内容安全
type MsgSec struct {
	Service     string     `json:"service"`       // 服务ID，固定值 wxee446d7507c68b11
	Api         string     `json:"api"`           // 接口名，固定值 msgSecCheck
	ClientMsgId string     `json:"client_msg_id"` // 随机字符串
	Data        MsgSecData `json:"data"`
}

type MsgSecData struct {
	Action string `json:"Action"` // 固定值 TextApproval
	Text   string `json:"Text"`   // 待检测的文本
}

type MsgSecRes struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	Data    string `json:"data"`
}

type ResData struct {
	Response ResDataResponse `json:"Response"`
}

type ResDataResponse struct {
	EvilTokens []ResEvilTokens `json:"EvilTokens"`
	RequestId  string          `json:"RequestId"`
}

type ResEvilTokens struct {
	EvilFlag     int      `json:"EvilFlag"`
	EvilType     int      `json:"EvilType"`
	EvilKeywords []string `json:"EvilKeywords"`
}

func NewMsgSec(msg string) *MsgSec {
	clientMsgId := utils.GetRandomString(32)
	msgSecData := MsgSecData{
		Action: "TextApproval",
		Text:   msg,
	}
	return &MsgSec{
		Service:     "wxee446d7507c68b11",
		Api:         "msgSecCheck",
		ClientMsgId: clientMsgId,
		Data:        msgSecData,
	}
}

func (m *MsgSec) Check() (bool, error) {
	accessToken, err := GetMiniAccessToken()
	if err != nil {
		return false, err
	}

	contentType := "application/json;charset=utf-8"
	reqUrl := fmt.Sprintf("https://api.weixin.qq.com/wxa/servicemarket?access_token=%s", accessToken)
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}
	content, err := json.Marshal(m)
	if err != nil {
		return false, err
	}
	resp, err := client.Post(reqUrl, contentType, strings.NewReader(string(content)))
	if err != nil {
		return false, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return false, err
	}

	msgSecRes := MsgSecRes{}
	err = json.Unmarshal(body, &msgSecRes)
	if err != nil {
		return false, err
	}

	res := ResData{}
	err = json.Unmarshal([]byte(msgSecRes.Data), &res)
	if err != nil {
		return false, err
	}

	for _, item := range res.Response.EvilTokens {
		if item.EvilType != 0 {
			return false, nil
		}
	}

	return true, nil
}
